package com.ihcy.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName 实现接口HandlerInterceptor 的拦截器
 * @Description
 * @Author ihcy
 * @Date 2019/12/11 9:58
 * @Version 1.0
 **/
public class MyInterceptor1 implements HandlerInterceptor {

    /**
     * 请求过来首先先走的方法，return true 继续执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("startTime",System.currentTimeMillis());
        System.out.println("============== MyInterceptor1 preHandle ============== ");
        return true;
    }

    /**
     * 请求之后，返回之前
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
       Long time = (Long) request.getAttribute("startTime");
        System.out.println("============== MyInterceptor1 postHandle, time : "+
                (System.currentTimeMillis()-time)+"============== ");
    }

    /**
     * 处理完成之后
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        request.removeAttribute("startTime");
        System.out.println("============== MyInterceptor1 afterCompletion============== ");
    }
}
